package com.demo.lifeinfo.common.home.fm;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.demo.lifeinfo.R;
import com.demo.lifeinfo.app.XBaseFragment;
import com.demo.lifeinfo.common.mine.MyLoveNews;
import com.demo.lifeinfo.common.mine.MyPublishAc;
import com.demo.lifeinfo.common.mine.MyReplyingAc;
import com.demo.lifeinfo.common.mine.PersonalnfoAc;
import com.demo.lifeinfo.common.publish.PublishActivity;
import com.demo.lifeinfo.common.sign.LoginActivity;
import com.demo.lifeinfo.entity.Option;
import com.demo.lifeinfo.entity.User;
import com.demo.lifeinfo.model.GlideApp;
import com.demo.lifeinfo.model.XPImageLoader;
import com.lxj.xpopup.XPopup;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.api.widget.Widget;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import de.hdodenhof.circleimageview.CircleImageView;
import jp.wasabeef.glide.transformations.BlurTransformation;

/**
 * created by Raymond
 * on 2019-04-24
 */
public class MineFm extends XBaseFragment {
    @BindView(R.id.nick_name)
    TextView nickName;
    private int mOffset = 0;
    private int mScrollY = 0;

    @BindView(R.id.mine_top_bg)
    ImageView mineTopBg;
    @BindView(R.id.circleImageView2)
    CircleImageView circleImageView2;


    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    BaseQuickAdapter<Option, BaseViewHolder> adapter;
    @BindView(R.id.smartLayout)
    SmartRefreshLayout smartLayout;

    User user;


    public static MineFm newInstance() {

        Bundle args = new Bundle();

        MineFm fragment = new MineFm();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fm_mine;
    }

    @SuppressLint("ResourceAsColor")
    @Override
    public void initView() {
//        GlideApp.with(this)
//                .load(R.drawable.ic_bg)
//                .apply(RequestOptions.bitmapTransform(new BlurTransformation(14, 3)))
//                .into(mineTopBg);
        smartLayout.setOnMultiPurposeListener(new SimpleMultiPurposeListener() {
            @Override
            public void onHeaderMoving(RefreshHeader header, boolean isDragging, float percent, int offset, int headerHeight, int maxDragHeight) {
                mOffset = offset / 2;
                mineTopBg.setTranslationY(mOffset - mScrollY);
            }
        });
        adapter = new BaseQuickAdapter<Option, BaseViewHolder>(R.layout.item_option) {
            @Override
            protected void convert(BaseViewHolder helper, Option item) {
                GlideApp.with(getActivity()).load(item.getIcon()).into((ImageView) helper.getView(R.id.imageView));
                helper.setText(R.id.tv_opt, item.getDesc());
                helper.addOnClickListener(R.id.btn_opt);
            }
        };
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                if (!BmobUser.isLogin()) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                    return;
                }

                switch (position) {
                    case 0:
                        Intent it = new Intent(getActivity(), PersonalnfoAc.class);
                        it.putExtra("user", BmobUser.getCurrentUser(User.class));
                        getActivity().startActivity(it);
                        break;
                    case 1:
                        Intent it2 = new Intent(getActivity(), MyPublishAc.class);
                        it2.putExtra("user", BmobUser.getCurrentUser(User.class));
                        getActivity().startActivity(it2);
                        break;
                    case 2:
                        startActivity(new Intent(getActivity(), MyLoveNews.class));
                        break;
                    case 3:
                        startActivity(new Intent(getActivity(), MyReplyingAc.class));
                        break;
                    default:
                        break;
                }

            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(adapter);
        adapter.addData(new Option(R.drawable.ic_info, "个人资料"));
        adapter.addData(new Option(R.drawable.ic_question_circle_fill, "我的发布"));
        adapter.addData(new Option(R.drawable.ic_star_fill, "我的喜欢"));
        adapter.addData(new Option(R.drawable.ic_star_fill, "我参与的"));
        adapter.addData(new Option(R.drawable.ic_team, "关于我们"));
        setViewData();
    }

    @Override
    public void initData() {

    }

    private void setViewData() {
        user = BmobUser.getCurrentUser(User.class);
        if (user == null) return;
        if (user.getAvatar() != null) {
            GlideApp.with(this)
                    .load(user.getAvatar().getFileUrl())
                    .error(R.mipmap.ic_launcher)
                    .placeholder(R.mipmap.ic_launcher)
                    .centerCrop()
                    .into(circleImageView2);
        }
        if (user.getImage() != null) {
            GlideApp.with(this)
                    .load(user.getImage().getFileUrl())
                    .error(R.drawable.ic_bg)
                    .centerCrop()
                    .apply(RequestOptions.bitmapTransform(new BlurTransformation(14, 3)))
                    .into(mineTopBg);
        } else {
            GlideApp.with(this)
                    .load(R.drawable.ic_bg)
                    .error(R.drawable.ic_bg)
                    .centerCrop()
                    .apply(RequestOptions.bitmapTransform(new BlurTransformation(14, 3)))
                    .into(mineTopBg);
        }

        nickName.setText(TextUtils.isEmpty(user.getNickeName()) ? "小名" : user.getNickeName());
    }

    @OnClick({R.id.mine_top_bg, R.id.circleImageView2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.mine_top_bg:

                break;
            case R.id.circleImageView2:
                if (user != null) {
                    openAblum(-1);
                } else {
                    getActivity().startActivity(new Intent(getActivity(), LoginActivity.class));
                }
                break;
        }
    }


    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        user = BmobUser.getCurrentUser(User.class);
        if (user != null && circleImageView2 != null) {
            setViewData();
        }
    }

    @SuppressLint("NewApi")
    private void openAblum(int type) {
        Album.image(getActivity())
                .singleChoice()
                .camera(false)
                .columnCount(4)
                .widget(Widget.newLightBuilder(getActivity())
                        .statusBarColor(getActivity().getColor(R.color.colorPrimary))
                        .toolBarColor(getActivity().getColor(R.color.colorPrimary))
                        .build())
                .onResult(new Action<ArrayList<AlbumFile>>() {
                    @Override
                    public void onAction(@NonNull ArrayList<AlbumFile> result) {

                        upLoadFile(result.get(0).getPath());
                    }
                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                        setViewData();
                    }
                })
                .start();

    }

    private void upLoadFile(String filePath) {
//        showProgressDialog();
        BmobFile bmobFile = new BmobFile(new File(filePath));
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {

                if (e == null) {
                    showError("上传成功");

                    user.setAvatar(bmobFile);
                    user.setImage(bmobFile);
                    user.update(user.getObjectId(), new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null) {
//                                loadImage(bmobFile.getFileUrl(), circleImageView2);
                                setViewData();
                            } else {
                                showError("更新失败，稍后再试！");
                                Log.e("xiaoqiang", e.getMessage() + e.getErrorCode());
                            }
                        }
                    });

                } else {
//                    dimssProgressDialog();
                    showError("更新失败，稍后再试！");
                    Log.e("xiaoqiang", e.getMessage() + "--" + e.getErrorCode());
                }
            }
        });
    }


    @OnClick(R.id.check_img_btn)
    public void onViewClicked() {
        if (user == null) return;
        new XPopup.Builder(getActivity())
                .asImageViewer(mineTopBg, user.getImage().getFileUrl(), -1, -1, 50, false, new XPImageLoader())
                .show();
    }
}
